from PyQt5.Qt import *
import os


class NoteexpressInitFunc(object):
    '''
    将excl中的数据挂载到qApp上
    '''
    def __init__(self, noteexpress_path):
        # excl文件路径
        self.ne_path = noteexpress_path
        # 当前 cur_sheet
        # self.cur_sheet = cur_type_name
        # excl文件中的数据
        self.ne_source_dict = {
            'name': 'noteexpress',
            'uni': {
                'file_path': noteexpress_path,
                'cur_type_name': '',
                # 'sheet_index': sheet_index
                # 'all_data': ''
            },
            'com': {
                'field_name_list': [],
                'field_content_list': []
            }
        }

    def noteexpress2qApp(self, ne_data):
        '''
        读取excl中的数据
        :return:
        '''
        print('ne_data: {0}'.format(ne_data))
        for key in ne_data:
            self.ne_source_dict['uni']['cur_type_name'] = key
            self.ne_source_dict['com']['field_name_list'] = ne_data[key][0]
            self.ne_source_dict['com']['field_content_list'] = ne_data[key][1:]
            print("self.ne_source_dict['com']['field_name_list']: {0}".format(len(self.ne_source_dict['com']['field_name_list'])))
            for li in self.ne_source_dict['com']['field_content_list']:
                print("len(li): {0}".format(len(li)))
            # qApp.cx_src = self.ne_source_dict
            print(qApp.cx_src)
            return self.ne_source_dict

        # # 获取最大列数
        # row_count = self.cur_sheet.nrows if self.cur_sheet.nrows < 11 else 11
        # for i in range(row_count):
        #     # field_count = len(self.cur_sheet.row_values(0))
        #     col_slice = self.cur_sheet.row_values(rowx=i)
        #     if i == 0:
        #         self.excl_source_dict['com']['field_name_list'] = col_slice
        #     else:
        #         self.excl_source_dict['com']['field_content_list'].append(col_slice)
        # print(self.excl_source_dict)
        # # excl表的前十条数据挂载到qApp中
        # qApp.cx_src = self.excl_source_dict

    def readNoteExpressAllHeads(self, f_path):
        """:param fpath:
        :return:
        noteExpress包括图书、期刊、章节等许多资料类型，导入时需要不同的导入模版
        diccview设置成数组，不同的资料类型返回不同的数据集。
        """
        with open(f_path, 'r', encoding='UTF-8', errors='ignore') as f:
            headls = []
            for line in f.readlines():
                if line != '\n':  # 记录没有结束
                    if line.startswith(('{',)) and "}:" in line:
                        cur_key = line.split("}:")[0]
                        cur_key = cur_key.split("{")[1]
                        if cur_key not in headls:
                            headls.append(cur_key)
                        # print(cur_key)
        # print(headls)
        return headls

    def readNoteExpress(self):
        """:param fpath:
        :return:
        noteExpress包括图书、期刊、章节等许多资料类型，导入时需要不同的导入模版
        diccview设置成数组，不同的资料类型返回不同的数据集。
        """
        dictview = []
        order = 1

        dic = {}  # 存放总数据，多个表（资料类型），每个表多个记录{表名：[[字段1，字段2，。],[a,b,..],[第二条记录],[..]]}
        # table=[]#一个表（资料类型），存放多个记录
        headls = self.readNoteExpressAllHeads(self.ne_path)
        rows = [''] * len(headls)  # record=[]#一条记录多个字段值
        heads = []  # 存放每种资料类型的字段
        type = []  # 存放资料类型
        # startrow=1
        key = ""
        with open(self.ne_path, 'r', encoding='UTF-8', errors='ignore') as f:
            try:
                for line in f.readlines():
                    if line != '\n':  # 记录没有结束
                        lines = line.split("}:")
                        if len(lines) > 1:
                            # print(len(lines))
                            if lines[0].split('{')[1] == "Reference Type":  # 新纪录的类型，一般是开始。
                                key = lines[1][0:len(lines[1]) - 1]
                                if key not in type:  # 新类型
                                    type.append(key)
                                    dic[key] = []
                                    dic[key].append(headls)
                                    # head=[]
                                # else:  # 不是新资料类型
                                #     head = dic.get(key)
                            else:  # 该记录其他字段
                                row = lines[1][0:len(lines[1]) - 1]
                                head = lines[0].split('{')[1]
                                # print('headls_start')
                                for i, hd in enumerate(headls):
                                    if head == hd:
                                        rows[i] = row
                        else:  # 内容有换行的情况
                            last = rows.pop()
                            crow = last + lines[0][0:len(lines[0]) - 1]
                            rows.append(crow)
                    else:  # 新的记录，可能有多个空行
                        if len(rows) > 0:
                            for vl in rows:
                                if vl != '':
                                    dic[key].append(rows)
                                    rows = [''] * len(headls)
                                    break
            except Exception as e:
                print(e)
                # root = Tk()
                # root.withdraw()
                # messagebox.showwarning('警告', '读取文件错误，请确认文件格式是否NoteExpress文件！')
                # return
            # self.ui.comboBox_table.addItems(type)
            # self.data = dic
            # self.dictview = dic.get(type[0])
            # self.ui.comboBox_table.setHidden(False)
            # self.prevrecord()
        return dic

    # def readNoteExpress(self):
    #     """:param fpath:
    #     :return:
    #     noteExpress包括图书、期刊、章节等许多资料类型，导入时需要不同的导入模版
    #     diccview设置成数组，不同的资料类型返回不同的数据集。
    #     """
    #     dictview = []
    #     order = 1
    #
    #     dic = {}  # 存放总数据，多个表（资料类型），每个表多个记录{表名：[[字段1，字段2，。],[a,b,..],[第二条记录],[..]]}
    #     # table=[]#一个表（资料类型），存放多个记录
    #     rows = []  # record=[]#一条记录多个字段值
    #     headls = []
    #     heads = []  # 存放每种资料类型的字段
    #     type = []  # 存放资料类型
    #     # startrow=1
    #     key = ""
    #     with open(self.ne_path, 'r', encoding='UTF-8') as f:
    #         try:
    #             for line in f.readlines():
    #                 if line != '\n':  # 记录没有结束
    #                     lines = line.split("}:")
    #                     if len(lines) > 1:
    #                         # print(len(lines))
    #                         if lines[0].split('{')[1] == "Reference Type":  # 新纪录的类型，一般是开始。
    #                             key = lines[1][0:len(lines[1]) - 1]
    #                             if key not in type:  # 新类型
    #                                 type.append(key)
    #                                 dic[key] = []
    #                                 # head=[]
    #                             else:  # 不是新资料类型
    #                                 head = dic.get(key)
    #                         else:  # 该记录其他字段
    #                             row = lines[1][0:len(lines[1]) - 1]
    #                             head = lines[0].split('{')[1]
    #                             # print('headls_start')
    #                             # for
    #                             #
    #                             # if head not in headls:
    #                             #     headls.append(head)
    #                             #     print('headls: {0}'.format(headls))
    #                             #     row = ''
    #                             # print('headls_end')
    #                             rows.append(row)
    #                             heads.append(head)
    #                     else:  # 内容有换行的情况
    #                         last = rows.pop()
    #                         crow = last + lines[0][0:len(lines[0]) - 1]
    #                         rows.append(crow)
    #                 else:  # 新的记录，可能有多个空行
    #                     if len(rows) > 0:
    #                         if len(dic[key]) == 0:
    #                             dic[key].append(heads)
    #                         # startrow=startrow+1
    #                         dic[key].append(rows)
    #                         # if startrow>11:break
    #                         rows = []
    #                         heads = []
    #                         key = ""
    #         except Exception as e:
    #             print(e)
    #             # root = Tk()
    #             # root.withdraw()
    #             # messagebox.showwarning('警告', '读取文件错误，请确认文件格式是否NoteExpress文件！')
    #             # return
    #         # self.ui.comboBox_table.addItems(type)
    #         # self.data = dic
    #         # self.dictview = dic.get(type[0])
    #         # self.ui.comboBox_table.setHidden(False)
    #         # self.prevrecord()
    #     return dic


# if __name__ == '__main__':
#     cur_dir = os.path.dirname(os.path.abspath(__file__))
#     fpath = cur_dir + '/26..TXT'
#     dic = readNoteExpress(fpath)
#     print(dic)


